﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.IO;

namespace Department.admin.Content
{
    public partial class EditDiscipline : System.Web.UI.Page
    {
        int lectID = -1;

        private string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["DepartmentConnectionString"].ConnectionString;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Request.IsAuthenticated)
            {
                Response.Redirect("/admin/Login.aspx");
            }
            if (Request.Params["ID"] == null) // Redirect user if the page is loaded without params
            {
                Response.Redirect("/admin/Content/ViewAllDisciplines.aspx");
            }

            this.Page.Title = "Редакция на дисциплина";

            AdminVariablesSingleton.configureCKEditor(ref TextBoxText);

            string text = null;

            bool isHidden = false;
            string id = Request.Params["ID"];
            if (!Page.IsPostBack)
            {
                if (!(id == null))
                {
                    SqlConnection conn = new SqlConnection(strConnString);

                    try
                    {
                        conn.Open();

                        //Gets the news heading
                        string sqlHeading = @"SELECT        DisciplineFromDB.DisciplineID, DisciplineFromDB.DisciplineName, DisciplineFromDB.Semester, Disciplines.Description, ISNULL(Disciplines.IsHidden, 0) 
                         AS IsHidden, ISNULL(Disciplines.ID, - 1) AS ID, Disciplines.DisciplineDbID, SpecialtiesFromDB.SpecID, SpecialtiesFromDB.SpecName, 
                         SpecialtiesFromDB.DepartmentID
                        FROM            SpecialtiesFromDB INNER JOIN
                                                    DisciplineFromDB ON SpecialtiesFromDB.SpecID = DisciplineFromDB.SpecID LEFT OUTER JOIN
                                                    Disciplines ON DisciplineFromDB.DisciplineID = Disciplines.DisciplineDbID
                        WHERE        (DisciplineFromDB.DisciplineID = @ID) AND (SpecialtiesFromDB.DepartmentID = dbo.uf_get_department_id())";
                        SqlCommand comHeading = new SqlCommand(sqlHeading, conn);
                        comHeading.Parameters.AddWithValue("@ID", id);
                        SqlDataReader reader = comHeading.ExecuteReader();

                        while (reader.Read())
                        {
                            try
                            {

                                isHidden = reader.GetBoolean(4);
                                text = reader.GetString(3);

                            }
                            catch (SqlNullValueException ec)
                            {
                                ec.ToString();
                            }
                        }
                        checkboxActive.Checked = isHidden;
                        TextBoxText.Text = text;
                    }
                    catch (SqlException sqle)
                    {
                        Response.Redirect("/admin/ErrorPage.aspx?type=sql&err=" + sqle.Message);
                    }
                    catch (Exception ex)
                    {
                        Response.Redirect("/admin/ErrorPage.aspx?type=1&err=" + ex.Message);
                    }
                    finally
                    {
                        conn.Close();
                    }
                }

            }

        }

        protected void buttonSubmit_Click(object sender, EventArgs e)
        {
            SqlConnection conn2 = new SqlConnection(strConnString);
            string idFromLecturersView = Request.Params["id"];
            try
            {
                conn2.Open();
                string sqlHeading = "SELECT DisciplineFromDB.DisciplineID, DisciplineFromDB.DisciplineName, DisciplineFromDB.Semester, Disciplines.Description, ISNULL(Disciplines.IsHidden, 0) AS IsHidden, ISNULL(Disciplines.ID, - 1) AS ID, Disciplines.DisciplineDbID, SpecialtiesFromDB.SpecID, SpecialtiesFromDB.SpecName FROM SpecialtiesFromDB INNER JOIN DisciplineFromDB ON SpecialtiesFromDB.SpecID = DisciplineFromDB.SpecID LEFT OUTER JOIN Disciplines ON DisciplineFromDB.DisciplineID = Disciplines.DisciplineDbID WHERE DisciplineFromDB.DisciplineID = @ID";
                SqlCommand comHeading = new SqlCommand(sqlHeading, conn2);
                comHeading.Parameters.AddWithValue("@ID", idFromLecturersView);
                SqlDataReader reader = comHeading.ExecuteReader();

                while (reader.Read())
                {

                    try
                    {
                        lectID = Convert.ToInt32(reader.GetValue(5));
                    }
                    catch (InvalidCastException exc)
                    {
                        lectID = -1;
                        exc.ToString();
                    }

                }
            }
            catch (SqlException sqle)
            {
                Response.Redirect("/admin/ErrorPage.aspx?type=sql&err=" + sqle.Message);
            }
            catch (Exception ex)
            {
                Response.Redirect("/admin/ErrorPage.aspx?type=1&err=" + ex.Message);
            }
            finally
            {
                conn2.Close();
            }


            SqlConnection conn = new SqlConnection(strConnString);
            try
            {
                conn.Open();
                string sqlUpdate;
                SqlCommand comUpdate = null;
                if (lectID != -1)
                {
                    sqlUpdate = "UPDATE Disciplines SET Description =@Description, IsHidden =@IsHidden WHERE ID = @ID";


                    comUpdate = new SqlCommand(sqlUpdate, conn);


                    comUpdate.Parameters.AddWithValue("@ID", lectID);
                    comUpdate.Parameters.AddWithValue("@Description", TextBoxText.Text);
                    comUpdate.Parameters.AddWithValue("@IsHidden", checkboxActive.Checked);

                }
                else
                {
                    sqlUpdate = "INSERT INTO Disciplines (Description, IsHidden, DisciplineDbID) VALUES (@Description, @IsHidden, @DisciplineDbID)";

                    comUpdate = new SqlCommand(sqlUpdate, conn);

                    comUpdate.Parameters.AddWithValue("@Description", TextBoxText.Text);
                    comUpdate.Parameters.AddWithValue("@IsHidden", checkboxActive.Checked);

                    comUpdate.Parameters.AddWithValue("@DisciplineDbID", idFromLecturersView);
                }

                comUpdate.ExecuteNonQuery();

            }
            catch (SqlException sqle)
            {
                Response.Redirect("/admin/ErrorPage.aspx?type=sql&err=" + sqle.Message);
            }
            catch (Exception ex)
            {
                Response.Redirect("/admin/ErrorPage.aspx?type=1&err=" + ex.Message);
            }
            finally
            {
                conn.Close();
            }

            Response.Redirect("~/admin/Content/ViewAllDisciplines.aspx");
        }
        protected void markInactiveButton_Click(object sender, CommandEventArgs e)
        {
            string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["DepartmentConnectionString"].ConnectionString;
            SqlConnection conn = new SqlConnection(strConnString);
            try
            {
                conn.Open();
                string sqlCommandText = "DELETE FROM LecturerDiscipline WHERE LecturerID = @LecID";
                SqlCommand insertDocument = new SqlCommand(sqlCommandText, conn);

                insertDocument.Parameters.AddWithValue("@LecID", e.CommandArgument);

                insertDocument.ExecuteNonQuery();
            }
            catch (SqlException sqle)
            {
                Response.Redirect("/admin/ErrorPage.aspx?type=sql&err=" + sqle.Message);
            }
            catch (Exception ex)
            {
                Response.Redirect("/admin/ErrorPage.aspx?type=1&err=" + ex.Message);
            }
            finally
            {
                conn.Close();
            }
            itemsView.DataBind();
        }

        protected void addALecturerToDiscipline_Click(object sender, EventArgs e)
        {
            string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["DepartmentConnectionString"].ConnectionString;
            SqlConnection conn = new SqlConnection(strConnString);
            try
            {
                conn.Open();

                string sqlCommandTextSelect = "SELECT ID FROM Disciplines WHERE DisciplineDbID = @Disc";
                SqlCommand selectDisc = new SqlCommand(sqlCommandTextSelect, conn);

                selectDisc.Parameters.AddWithValue("@Disc", Request.Params["ID"]);

                int discID = Convert.ToInt32(selectDisc.ExecuteScalar());

                string sqlCommandText = "INSERT INTO LecturerDiscipline VALUES (@DiscID, @LectID)";
                SqlCommand insertLect = new SqlCommand(sqlCommandText, conn);

                insertLect.Parameters.AddWithValue("@LectID", lecturersDropDownList.SelectedValue);
                insertLect.Parameters.AddWithValue("@DiscID", discID);

                insertLect.ExecuteNonQuery();
            }
            catch (SqlException sqle)
            {
                Response.Redirect("/admin/ErrorPage.aspx?type=sql&err=" + sqle.Message);
            }
            catch (Exception ex)
            {
                Response.Redirect("/admin/ErrorPage.aspx?type=1&err=" + ex.Message);
            }
            finally
            {
                conn.Close();
            }
            itemsView.DataBind();
        }
    }

}